<template>
  <div class="modify-dialog">
    <slot>
      <el-button size="small" type="primary" @click="showDialog()">
        录入订单
      </el-button>
      <!--<el-button size="small" type="primary" @click="showDialogLr()">
       录入材料订单
     </el-button>-->
      <el-button size="small" type="primary" @click="contactList">
        合同列表
      </el-button>
    </slot>
    <!-- 录入订单 -->
    <el-dialog
      :close-on-click-modal="false"
      v-bind="dialogOpts"
      :visible.sync="dialogVisible"
      style="height: calc(100vh - 50px); overflow-y: scroll"
    >
      <Form v-bind="formOpts" v-on="formEvent">
        <template #formBtn>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onConfirm" v-preventReClick>
              确 定</el-button
            >
          </div>
        </template>
      </Form>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogOpen"
      center
      width="40%"
      title="录入订单"
      top="50px"
      :close-on-click-modal="false"
      v-if="dialogOpen"
    >
      <!-- <template slot="title">
        <div
          class="custom-header"
          :style="{
            color: '#fff',
            height: '50px',
            lineHeight: '50px',
          }"
        >
          {{ '录入订单' }}
        </div>
      </template> -->
      <div class="flexBox">
        <p>
          <span>店铺名称：</span>
          <el-input
            size="small"
            style="width: 230px"
            placeholder="请输入店铺名称"
            v-model="data.storeName"
          ></el-input>
        </p>
        <p>
          <span>付款方式：</span>
          <el-select
            size="small"
            style="width: 230px"
            placeholder="请选择付款方式"
            v-model.number="data.paymentMethod"
          >
            <el-option
              v-for="(item, index) in payTypeList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <div class="flexBox">
        <p>
          <span>材料付款金额：</span>
          <el-input
            size="small"
            type="number"
            style="width: 230px"
            placeholder="请输入付款金额"
            v-model="data.materialPayMoney"
          ></el-input>
        </p>
        <p>
          <span>材料下单金额：</span>
          <el-input
            size="small"
            type="number"
            style="width: 230px"
            placeholder="请输入下单金额"
            v-model="data.materialPlaceMoney"
          ></el-input>
        </p>
      </div>
      <!-- <div class="flexBox"> -->
      <!-- <p>
          <span>品牌类型：</span>
          <el-select
            size="small"
            style="width: 230px"
            placeholder="请选择品牌类型"
            v-model.number="data.systemType"
          >
            <el-option
              v-for="(item, index) in ppTypeList"
              :key="index"
              :label="item.systemName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p> -->

      <!-- </div> -->
      <div
        class="flexBox"
        style="justify-content: flex-start; padding-left: 16px"
      >
        <p style="margin-right: 30px">
          <span>付款时间：</span>
          <el-date-picker
            style="width: 230px"
            clearable
            size="small"
            value-format="yyyy-MM-dd"
            placeholder="请选择材料付款时间"
            v-model="data.materialPayTime"
          ></el-date-picker>
        </p>
        <p>
          <span>所属区域：</span>
          <el-select
            size="small"
            style="width: 230px"
            placeholder="请选择订单所属区域"
            v-model="data.area"
          >
            <el-option
              :label="item.areaName"
              :value="item.area"
              :key="item.area"
              v-for="item in areaData"
            ></el-option>
          </el-select>
        </p>
      </div>
      <div
        class="flexBox"
        style="justify-content: flex-start; padding-left: 16px"
      >
        <p style="display: flex">
          <span style="width: 99px">付款凭证：</span>
          <uploader v-model="payImg" :isDrag="true"></uploader>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="dialogOpen = false">取 消</el-button>
        <el-button @click="_submitNew" type="primary">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uploader from '../../../components/Element/UploaderNew.vue'
import modifyMixins from '@/mixins/modifyMixins.vue'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import * as XLSX from 'xlsx-js-style'
import Modify from './Modify.vue'

export default {
  mixins: [modifyMixins],
  components: {
    uploader,
  },
  data() {
    return {
      areaData: [],
      payTypeList: [],
      payTypeList: [],
      dialogOpen: false,
      labelPosition: 'left',
      araaList: [],
      fileList: [],
      form: {
        storeName: {
          tag: 'el-input',
          label: '订单名称',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入订单名称',
          },
        },
        deliveryDate: {
          tag: 'el-date-picker',
          label: '发货日期',
          value: '',
          props: {
            clearable: true,
            placeholder: '请选择出库时间',
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
        customPhone: {
          tag: 'el-input',
          label: '客户联系方式',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入客户联系方式',
          },
        },
        orderType: {
          tag: 'el-select',
          label: '订单类型',
          value: '',
          items: [
            { label: '新增店铺', value: 1 },
            { label: '老店升级', value: 2 },
          ],
          props: {},
        },
        area: {
          tag: 'el-select',
          label: '区域',
          value: '',
          items: [],
          props: {},
        },
        address: {
          tag: 'el-input',
          label: '发货地址',
          value: '',
          props: {
            type: 'textarea',
            clearable: true,
            placeholder: '请输入地址',
          },
        },
        expressCharge: {
          tag: 'el-input',
          label: '快递费用',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入费用',
          },
        },
        distance: {
          tag: 'el-input',
          label: '距离',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入距离（/米）',
          },
        },
        goodsPaymentMethod: {
          tag: 'el-select',
          label: '付款方式',
          value: '',
          items: [],
          props: {},
        },
        payMoney: {
          tag: 'el-input',
          label: '实付金额',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入',
          },
        },
        storeArea: {
          tag: 'el-input',
          label: '面积/平方',
          value: '',
          props: {
            clearable: true,
            placeholder: '请输入',
          },
        },
        payTime: {
          tag: 'el-date-picker',
          label: '付款时间',
          value: '',
          props: {
            clearable: true,
            placeholder: '请选择付款时间',
            pickerOptions: {
              // disabledDate (time) {
              // 	return time.getTime() < dayjs().startOf("day").valueOf();
              // },
            },
          },
        },
        isHistoryOrder: {
          tag: 'el-select',
          label: '是否为遗留订单',
          value: 2,
          items: [
            { label: '是', value: 1 },
            { label: '否', value: 2 },
          ],
          props: {},
        },
        isPerSale: {
          tag: 'el-select',
          label: '预售单',
          value: '',
          items: [
            { label: '是', value: 1 },
            { label: '否', value: 2 },
          ],
          props: {},
        },
        isKaYou: {
          tag: 'el-switch',
          label: '是否使用卡游层板',
          value: 0,
          props: {
            activeValue: 1, // 开启时的值
            inactiveValue: 0, // 关闭时的值
          },
        },
        storeImgs: {
          tag: 'Uploader',
          label: '营业区原始图',
          value: [],
          props: {},
        },
        storageOriginImg: {
          tag: 'Uploader',
          label: '仓库原始图',
          value: [],
          props: {},
        },
      },
      payImg: '', //付款凭证
      data: {
        systemType: 1,
        materialPlaceMoney: 0, //下单金额
        materialPayMoney: 0, //付款金额
        materialPayVoucher: '', //付款凭证
        paymentMethod: null, //付款方式 1 9076 2 5127 3 6666 4 曹总微信 5 财务2微信 6 曹总支付宝
        storeName: '', //店铺名称
        materialPayTime: '', //材料付款时间
        // deliveryDate: '',
        // customPhone: '',
        // orderType: '',
        area: '', //所属区域(仓库)
      },
    }
  },
  computed: {
    ...mapState(['token']),
    preImgs() {
      return this.fileList.map((e) => `${this.$imgHost}${e}`)
    },
    title() {
      return (this.modify === 'add' ? '新增' : '编辑') + '订单'
    },
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  created() {},
  methods: {
    async _submitNew() {
      let form = this.data
      if (!form.storeName) {
        return this.$message.warning('请输入店铺名称！')
      }
      if (!form.paymentMethod) {
        return this.$message.warning('请选择付款方式！')
      }
      if (!form.materialPayMoney || form.materialPayMoney < 0) {
        return this.$message.warning('请输入正确的付款金额！')
      }
      if (!form.materialPlaceMoney || form.materialPlaceMoney < 0) {
        return this.$message.warning('请输入正确的下单金额！')
      }
      // if (!form.systemType) {
      //   return this.$message.warning('请选择品牌类型！')
      // }
      if (!form.area) {
        return this.$message.warning('请选择所属区域！')
      }
      if (!form.materialPayTime) {
        return this.$message.warning('请选择付款时间！')
      }
      if (!this.payImg) {
        return this.$message.warning('请上传付款凭证！')
      }

      form.materialPayVoucher = this.payImg
      try {
        const apiMap = {
          新增: this.$api.orderAdd,
          编辑: '',
        }
        const apiFunc = apiMap['新增']
        if (!apiFunc) return
        const resDate = await apiFunc(form)
        console.log('新增结果', resDate)

        this.$message.success(`录入成功！`)
        this.dialogOpen = false
        this.submitDoneMsg()
      } catch (err) {
        console.error('接口请求出错：', err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    async getPayType() {
      const res = await this.$api.orderGetPaymentMethod()
      const res2 = await this.$api.areaLedgerAreaList()

      console.log('付款类型', res)
      if (res && res.length) {
        this.payTypeList = []
        this.payTypeList = res
      }
      if (res2 && res2.length) {
        this.areaData = []
        this.areaData = res2
      }
    },
    onSuccess(res) {
      const { fileList = [] } = this
      if (res.code == 200 && res.result) {
        fileList.push(res.result[0])
        this.fileList = fileList
      }
    },
    contactList() {
      this.$api
        .contractGetContractList({ pageSize: 10000, pageNumber: 1 })
        .then((res) => {
          const wb = XLSX.utils.book_new()
          let data = []
          data = [['序号  ', '店铺名', '联系人', '身份证', '总金额']]
          res.map((el, index) => {
            data.push([
              index + 1,
              el.storeName,
              el.customerName,
              el.customerIdCard,
              el.totalPrice,
            ])
          })
          const ws = XLSX.utils.aoa_to_sheet(data)
          ws['!cols'] = [
            { wpx: 50 }, // 第一列宽度为250单位
            { wpx: 200 }, // 第二列宽度为300单位
            { wpx: 100 }, // 第三列宽度为350单位
            { wpx: 200 },
            { wpx: 100 },
          ]
          ws['A1'].s = {
            alignment: { horizontal: 'center' },
            font: { blod: true, color: { rgb: '000000' } },
            fill: { fgColor: { rgb: 'ff6a00' } },
          }
          // ws["A2"].s = {
          //   alignment: { horizontal: 'center' },
          // }
          // 将工作表添加到工作簿
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

          ws['!merges'] = []
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

          // 创建一个 Blob 对象
          const blob = new Blob([s2ab(wbout)], {
            type: 'application/octet-stream',
          })

          // 使用 Blob 对象创建一个链接
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = `合同列表.xlsx`

          // 触发下载
          link.click()

          // 清理
          URL.revokeObjectURL(link.href)

          function s2ab(s) {
            const buf = new ArrayBuffer(s.length)
            const view = new Uint8Array(buf)
            for (let i = 0; i !== s.length; ++i)
              view[i] = s.charCodeAt(i) & 0xff
            return buf
          }
        })
    },
    showDialogLr() {
      this.getPayType()
      this.data = this.$options.data.call(this).data
      this.payImg = ''
      this.dialogOpen = true
    },
    showDialog(modify = 'add', row = {}) {
      this.$api.areaLedgerAreaList().then((res) => {
        const araaList = res.map((item) => ({
          label: item.areaName,
          value: item.area,
        }))
        this.form.area.items = araaList
      })
      // 付款方式
      this.$api.orderGetPaymentMethod().then((res) => {
        const method = res.map((item) => ({
          label: item.name,
          value: item.id,
        }))
        this.form.goodsPaymentMethod.items = method
      })

      this.dialogVisible = true
      this.row = row
      this.modify = modify || 'add'
      // 	let defValue = "";
      // 	if (Array.isArray(this.form[key].value)) defValue = [];
      // 	if (Object.hasOwnProperty.call(row, key)){
      // 		console.log(this.form[key].value,this.form[key],'key')
      // 		if(key || key === 0){
      // 			 this.form[key].value = row[key];
      // 	    }
      // 		else { this.form[key].value =  defValue;}
      // 	}
      // 	else{
      // 		this.form[key].value = defValue;
      // 	}
      // if (this.modify == 'add') {
      //   for (const key in this.form) {
      //   if (key === 'isDebt') {
      //     delete this.form[key];
      //   }}
      // }else{
      //   if (!('isDebt' in this.form)) {
      //     this.form.isDebt = {
      //       tag: "el-select",
      //       label: "是否欠款",
      //       value:'',
      //       items: [
      //         {label: "有欠款", value: 0},
      //         {label: "已结清", value: 1},
      //       ],
      //     };
      //   }
      // }
      for (const key in this.form) {
        let defValue = ''
        if (Array.isArray(this.form[key].value)) defValue = []
        if (Object.hasOwnProperty.call(row, key))
          this.form[key].value = row[key] || defValue
        else this.form[key].value = defValue
      }
      this.formKey = this.$quinn.guid()
    },
    onSubmit(form) {
      const { modify, row } = this
      let { deliveryDate, payTime, isPerSale } = form
      const { id } = row
      payTime = dayjs(payTime)
      deliveryDate = dayjs(deliveryDate)
      if (!deliveryDate.isValid()) {
        form.deliveryDate = ''
        // return this.$message.error("请选择时间");
      } else form.deliveryDate = deliveryDate.format('YYYY-MM-DD')
      if (!payTime.isValid()) {
        delete form.payTime
        // return this.$message.error("请选择时间");
      } else form.payTime = payTime.format('YYYY-MM-DD')
      form.id = id
      form.systemType = 1
      if (!/^\d+$/.test(form.distance))
        return this.$message.warning('距离应为纯数字！')
      if (!form.goodsPaymentMethod)
        return this.$message.warning('请选择付款方式！')
      if (!isPerSale) return this.$message.warning('是否为预售单必填！')
      // newOrderUpdate
      this.$api[modify === 'add' ? 'newOrderCreate' : 'orderOrderInfoUpdate'](
        form
      ).then(this.submitDoneMsg)
    },
    onRemove(e, i) {
      this.fileList = this.fileList.filter((item, index) => index != i)
    },
  },
}
</script>

<style lang="less" scoped>
.flexBox {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;

  span {
    // width: 80px;
    width: 99px;
    display: inline-block;
  }
}
</style>
